/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FindReplace.java
 *
 * Created on 13.Haz.2009, 13:14:38
 */

package com.meraklisina.latexeditor;

import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;
import java.awt.TrayIcon.MessageType;
import java.awt.event.KeyListener;
import javax.swing.*;

/**
 *
 * @author eozkanal
 */
public class GoToLine extends javax.swing.JPanel implements KeyListener {
    private JTextPane textEditor;
    private JDialog dialog;
    private JTabbedPane tab_Editors;
    /** Creates new form FindReplace */
    public GoToLine(JDialog jd, JTabbedPane editors) {
        this.dialog=jd;
        this.tab_Editors=editors;

        this.setFocusable(true);
        this.addKeyListener(this);

        initComponents();

        TxtLineNumber.addKeyListener(this);
        BtnGoToLine.addKeyListener(this);
        BtnCancel.addKeyListener(this);
    }

    /** Returns active JTextPane object
     */
    public JTextPane getTextEditor()
    {
        return new TextEditors().GetJTextPaneAt(this.tab_Editors, this.tab_Editors.getSelectedIndex());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

    	BtnGoToLine = new javax.swing.JButton();
        BtnCancel = new javax.swing.JButton();
        TxtLineNumber = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        
        lang.LoadLanguage(BlueLatexEditor._language);

        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        BtnGoToLine.setText(lang.GoTo);
        BtnGoToLine.setName("BtnGoToLine"); // NOI18N
        BtnGoToLine.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	BtnGoToLineActionPerformed(evt);
            }
        });

        BtnCancel.setText(lang.Cancel);
        BtnCancel.setName("BtnCancel"); // NOI18N
        BtnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnCancelActionPerformed(evt);
            }
        });

        TxtLineNumber.setName("TxtLineNumber"); // NOI18N

        jLabel1.setText(lang.LineNumber + ":");
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(TxtLineNumber, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(BtnCancel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(BtnGoToLine, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BtnGoToLine)
                    .addComponent(TxtLineNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(BtnCancel)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        
    }// </editor-fold>//GEN-END:initComponents

    Language lang = new Language();
    /** Searchs text entered at active editor tab and selects it. If cannot found displays
     * a message box
     */
    private void GoToSelectedLine(int line)
    {
    	JTextPane selectedEditor = getTextEditor();
    	StringBuffer sb = new StringBuffer(selectedEditor.getText());
    	
        int j=1;
        for(int i=0; i<sb.length(); i++) {
           if(sb.charAt(i)=='\n')j++;
              if(j==line){
                j=i;
                break;
              }
        }
        
        if (line == 1)
        {
        	j = 0;
        }
        else if (line > j)
    	{
    		JOptionPane.showMessageDialog(null, "There is less line than the specified number", "Error", JOptionPane.ERROR_MESSAGE);
    		return;
    	}
        else if (line < 0)
        {
        	JOptionPane.showMessageDialog(null, "You cannot go to this line", "Error", JOptionPane.ERROR_MESSAGE);
    		return;
        }
        
        try{
        	selectedEditor.requestFocus();
        	selectedEditor.setCaretPosition(j+2-line);
        }catch (IllegalArgumentException exc) { System.err.println("goToLine() "+exc); }
    }
    
    private void BtnGoToLineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnFindNextActionPerformed
    	try{
    		int lineNumber = Integer.parseInt(TxtLineNumber.getText().trim());
        	GoToSelectedLine(lineNumber);	
    	} catch (Exception ee)
    	{
    		JOptionPane.showMessageDialog(null, "Please enter a number", "Error", JOptionPane.ERROR_MESSAGE);
    		TxtLineNumber.setText("");
    	}
    	
    }

    private void BtnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCancelActionPerformed
        this.dialog.setVisible(false);
    }

    public void keyPressed(java.awt.event.KeyEvent evt)
	{
	        if(evt.getKeyCode()==evt.VK_ESCAPE)
	            this.dialog.setVisible(false);
	}
	public void keyTyped(java.awt.event.KeyEvent ke){}
	public void keyReleased(java.awt.event.KeyEvent ke){}
	    
    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_formKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtnCancel;
    private javax.swing.JButton BtnGoToLine;
    private javax.swing.JTextField TxtLineNumber;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables

}
